package com.empire.devops.emops.es.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.empire.devops.emops.common.BaseResponse;
import com.empire.devops.emops.es.entity.OpsGroupEntity;
import com.empire.devops.emops.es.service.IOpsGroupService;
import com.empire.devops.emops.es.vo.OpsGroupDetailVO;
import com.empire.devops.emops.es.vo.OpsGroupQueryVO;
import com.empire.devops.emops.es.vo.OpsGroupVO;
import com.empire.devops.emops.utils.PageResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xutenglong
 * @since 2023-01-01
 */
@Api(tags = "项目组API")
@ApiSort(3)
@RestController
@RequestMapping("/opsGroup")
@Slf4j
public class OpsGroupController {
    private final IOpsGroupService opsGroupService;

    @Autowired
    public OpsGroupController(IOpsGroupService opsGroupService) {
        this.opsGroupService = opsGroupService;
    }

    @ApiOperation(value = "新增项目分组接口", notes = "新增项目分组接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "addOpsGroup", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<Void> addOpsGroup(@RequestBody OpsGroupVO opsGroupVO) {
        log.info("调用addOpsGroup();param:{}", JSON.toJSONString(opsGroupVO));
        try {
            OpsGroupEntity opsGroupEntity = opsGroupVO.toOpsGroupEntity();
            Date now = new Date();
            opsGroupEntity.setCreateTime(now);
            opsGroupService.save(opsGroupEntity);
        } catch (Exception e) {
            log.error("addOpsGroup()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }

    @ApiOperation(value = "更新项目分组接口", notes = "更新项目分组接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "updateOpsGroup", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<Void> updateOpsGroup(@RequestBody OpsGroupVO opsGroupVO) {
        log.info("updateOpsGroup();param:{}", JSON.toJSONString(opsGroupVO));
        try {
            OpsGroupEntity opsGroupEntity = opsGroupVO.toOpsGroupEntity();
            Date now = new Date();
            opsGroupEntity.setUpdateTime(now);
            opsGroupService.updateById(opsGroupEntity);
        } catch (Exception e) {
            log.error("updateOpsGroup()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }

    @ApiOperation(value = "查询项目分组列表接口", notes = "查询项目分组列表接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "queryPage", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<PageResult<OpsGroupDetailVO>> queryPage(@RequestBody OpsGroupQueryVO opsGroupQueryVO) {
        log.info("queryPage();param:{}", JSON.toJSONString(opsGroupQueryVO));
        try {
            LambdaQueryWrapper<OpsGroupEntity> opsGroupWrapper = Wrappers.lambdaQuery();
            if (StringUtils.isNotBlank(opsGroupQueryVO.getGroupName())) {
                opsGroupWrapper.like(OpsGroupEntity::getGroupName, opsGroupQueryVO.getGroupName());
            }
            if (StringUtils.isNotBlank(opsGroupQueryVO.getEmail())) {
                opsGroupWrapper.like(OpsGroupEntity::getEmail, opsGroupQueryVO.getEmail());
            }
            if (StringUtils.isNotBlank(opsGroupQueryVO.getRemark())) {
                opsGroupWrapper.like(OpsGroupEntity::getRemark, opsGroupQueryVO.getRemark());
            }
            PageResult<OpsGroupDetailVO> pageResult = new PageResult<>();
            // 两个参数：current的值默认是1，从1开始，不是0。size是每一页的条数。
            Page<OpsGroupEntity> page = new Page<>(opsGroupQueryVO.getPage(), opsGroupQueryVO.getPageSize());
            Page<OpsGroupEntity> opsGroupPage = opsGroupService.page(page, opsGroupWrapper);
            List<OpsGroupDetailVO> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(opsGroupPage.getRecords())) {
                opsGroupPage.getRecords().forEach(item -> list.add(OpsGroupDetailVO.newInstance(item)));
            }
            pageResult.setList(list);
            pageResult.setCount(((Long) opsGroupPage.getTotal()).intValue());
            return BaseResponse.success(pageResult);
        } catch (Exception e) {
            log.error("queryPage()", e);
            return BaseResponse.fail("系统繁忙");
        }

    }

    @ApiOperation(value = "获取项目组列表接口", notes = "获取项目组列表接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "/getOpsGroupList", method = {RequestMethod.GET}, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<List<OpsGroupDetailVO>> getOpsGroupList() {
        List<OpsGroupDetailVO> list = new ArrayList<>();
        try {
            List<OpsGroupEntity> opsProjectList = opsGroupService.list();
            if (!CollectionUtils.isEmpty(opsProjectList)) {
                opsProjectList.forEach(item -> list.add(OpsGroupDetailVO.newInstance(item)));
            }
        } catch (Exception e) {
            log.error("getOpsGroupList()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success(list);
    }

    @ApiOperation(value = "删除项目分组接口", notes = "删除项目分组接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "/deleteOpsGroup/{id}", method = {RequestMethod.DELETE}, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<Void> deleteOpsGroup(@PathVariable("id") Integer id) {
        log.info("deleteOpsGroup();param:{}", id);
        try {
            opsGroupService.removeById(id);
        } catch (Exception e) {
            log.error("deleteOpsGroup()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }
}
